package com.tansun.rule.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.tansun.rule.config.AppConfiguration;
import com.tansun.rule.pojo.User;
import com.tansun.rule.service.SecurityService;
import com.tansun.rule.utils.IOUtils;
/**
 * 系统管理部分
 * @author Administrator
 *
 */
@Service("securityService")
public class SecurityServiceImpl implements SecurityService {

	/**
	 * 登录验证
	 */
	public User validateUser(String userName, String password, String path){
		if(StringUtils.isBlank(userName) || StringUtils.isBlank(password)){
			return null;
		}
		File file = new File(".");
		String message = IOUtils.getLineByhead(new File(path), userName);
		if(null == message){
			return null;
		}
		String[] userMess = message.split(":");
		if(!password.equals(userMess[1])){
			return null;
		}
		User user = new User();
		user.setUserName(userMess[0]);
		user.setPassWord(userMess[1]);
		user.setId(userMess[2]);
		if("admin".equals(userName)){
			String[] aa = AppConfiguration.RuleProjMap.keySet().toArray(new String[0]);
			user.setContrlRuleProject(aa);
		}else{
			user.setContrlRuleProject(userMess[3].split(","));
			
		}
		//user.setTestRuleProject(userMess[3].split(";"));
		user.setColor(userMess[4]);
		user.setLayout(userMess[5]);
		user.setLanuage(userMess[6]);
		return user;
	}
	public boolean validateUserNameExsit(String userName, String id, String path){
		String message = IOUtils.getLineByhead(new File(path), userName);
		if(null != message){
			if(id.equals(message.split(":")[2])){
				return true;
			}else{
				return false;
			}
		}
		return true;
	}
	public boolean validateUserNameExsit(String userName, String path){
		
		String message = IOUtils.getLineByhead(new File(path), userName);
		if(null != message){
			return false;
		}
		return true;
	}
	/**
	 * 验证某个用户是否有某个项目的权限
	 */
	public User validateUserByProj(String userName, String password, String ruleProj, String path){
		if(StringUtils.isBlank(userName) || StringUtils.isBlank(password)){
			return null;
		}
		File file = new File(".");
		String message = IOUtils.getLineByhead(new File(path), userName);
		if(null == message){
			return null;
		}
		String[] userMess = message.split(":");
		if(!password.equals(userMess[1])){
			return null;
		}
		if(!userName.equals("admin") && (StringUtils.isBlank(ruleProj) || (ruleProj+",").indexOf(userMess[2]+",")<0)){
			return null;
		}
		User user = new User();
		user.setUserName(userMess[0]);
		user.setPassWord(userMess[1]);
		user.setId(userMess[2]);
		user.setContrlRuleProject(userMess[3].split(";"));
		//user.setTestRuleProject(userMess[3].split(";"));
		user.setColor(userMess[4]);
		user.setLayout(userMess[5]);
		user.setLanuage(userMess[6]);
		return user;
	}
	/**
	 * 用户更新
	 */
	public boolean updateUser(String id, User user, String path) {
		//按照id查找
		String line = IOUtils.getFirstLineByPatternStr("^[a-z,A-Z,0-9,_]*:[a-z,A-Z,0-9,_]*:"+id+":.*",path);
		String[] lineItmes =  line.split(":");
		
		if(StringUtils.isNotBlank(user.getUserName())){
			lineItmes[0]= user.getUserName();
		}
		if(StringUtils.isNotBlank(user.getPassWord())){
			lineItmes[1]= user.getPassWord();
		}
		lineItmes[2]= id;
		if(user.getContrlRuleProject()!=null && user.getContrlRuleProject().length>0){
			lineItmes[3]= arrayToString(user.getContrlRuleProject(),",");
		}else{
			lineItmes[3]="";
		}
		if(StringUtils.isNotBlank(user.getColor())){
			lineItmes[4]= user.getColor();
		}
		if(StringUtils.isNotBlank(user.getLayout())){
			lineItmes[5]= user.getLayout();
		}
		if(StringUtils.isNotBlank(user.getLanuage())){
			lineItmes[6]= user.getLanuage();
		}
		
		String lined = arrayToString(lineItmes,":");
		IOUtils.modifyFirstLineByPatternStr(lined, "^[a-z,A-Z,0-9,_]*:[a-z,A-Z,0-9,_]*:"+id+":.*", path);
		
		return true;
	}
	/**
	 * 用户删除
	 */
	public boolean delUser(String id, String path) {
		boolean result = IOUtils.modifyFirstLineByPatternStr(null,"^[a-z,A-Z,0-9,_]*:[a-z,A-Z,0-9,_]*:"+id+":.*",path);
		return result;
	}
	/**
	 * 用户添加
	 */
	public boolean addUser(User user, String path) {
		String line = user.getUserName()+":";
		line = line + user.getPassWord() +":";
		line = line + user.getId() +":";
		line = line + arrayToString(user.getContrlRuleProject(),",") +":";
		line = line + user.getColor() +":";
		line = line + user.getLayout() +":";
		line = line + user.getLanuage();
		
		IOUtils.appendFileALine(line, path);
		return false;
	}
	/**array string convert*/
	public String arrayToString(String[] args, String splitStr) {
		String result = "";
		if(args==null){
			return result;
		}
		for (int i = 0; i < args.length; i++) {
			result = result + args[i]+ ((i == (args.length-1))?"":splitStr);
		}
		return result;
	}
	/**获取所有用户*/
	public List<User> getUsersFromFile(String path) {
		List<User> users = new ArrayList<User>();
		try {
			List<String> strings = FileUtils.readLines(new File(path), "UTF-8");
			for (String string : strings) {
				if(!"".equals(string.trim()) && !string.startsWith("#")){
					User user = new User();
					String[] items = string.split(":");
					user.setUserName(items[0]);
					user.setPassWord(items[1]);
					user.setId(items[2]);
					user.setContrlRuleProject(items[3].split(","));
					user.setColor(items[4]);
					user.setLayout(items[5]);
					user.setLanuage(items[6]);
					users.add(user);
					
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return users;
	}
	public User getUserById(String userId, String path){
		File file = new File(".");
//		System.out.println(file.getAbsolutePath());
		String message = IOUtils.getFirstLineByPatternStr("^[a-z,A-Z,0-9,_]*:[a-z,A-Z,0-9,_]*:"+userId+":.*",path);
		if(null == message){
			return null;
		}
		String[] userMess = message.split(":");
		User user = new User();
		user.setUserName(userMess[0]);
		user.setPassWord(userMess[1]);
		user.setId(userMess[2]);
		if("admin".equals(user.getUserName())){
			
		}else{
			user.setContrlRuleProject(userMess[3].split(","));
			
		}
		//user.setTestRuleProject(userMess[3].split(";"));
		user.setColor(userMess[4]);
		user.setLayout(userMess[5]);
		user.setLanuage(userMess[6]);
		return user;
	}
}
